/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package be.cultuurschuur.services;

import be.cultuurschuur.Controllers.*;
import be.cultuurschuur.entity.*;
import be.cultuurschuur.interfaces.*;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.faces.context.*;
import javax.persistence.*;


/**
 *
 * @author Webbie
 */
public class BLBestemming implements BestemmingInterface
{
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("cultuurschuurPU");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    
    private Continent continent;
    private String naam;

    public Continent getContinent() {
        return continent;
    }

    public void setContinent(int continentId) {
        BLContinent blContinent = new BLContinent();
        this.continent = blContinent.getContinentbyId(continentId);
    }

    public String getNaam() {
        return naam;
    }

    public void setNaam(String naam) {
        this.naam = naam;
    }

    @Override
    public Bestemming insertBestemming(){ 
        
        tx.begin();
        Bestemming bestemming = new Bestemming();
        bestemming.setContinent(continent);
        bestemming.setNaam(naam);
        
        em.persist(bestemming);
        tx.commit();
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("bestemming.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(VervoerController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return bestemming;
    }
    
    @Override
    public List<Bestemming> getBestemmingen(){
        return em.createNamedQuery("Bestemming.getAll").getResultList();
    }
    @Override
    public Bestemming getBestemmingById(int id)
    {
        Query q = em.createNamedQuery("Bestemming.getById");
         q.setParameter(1, id);
        Bestemming bestemming = (Bestemming)q.getSingleResult();
        return bestemming;
    }
    @Override
    public Bestemming updateBestemming(Bestemming bestemming)
    {
        tx.begin();

        Bestemming b = em.find(Bestemming.class, bestemming.getId());
        b.setContinent(bestemming.getContinent());
        b.setNaam(bestemming.getNaam());
       
        em.persist(b);

        tx.commit();
        return b;
    }
    @Override
    public boolean deleteBestemming(int id)
    {
        try {
            tx.begin();

            Bestemming b = em.find(Bestemming.class, id);
            em.remove(b);
            tx.commit();
            return true;
        } catch (Exception exc) {
            return false;
        }
    }
}
